/* 与项目无关的 TodoList */
import React, { Component,Fragment } from 'react';
import TodoItem from './TodoItem';
import './index.css'

// 定义react组件
class TodoList extends Component {
    constructor(props){
        super(props)
        this.state ={
            list: [],
            inputValue: ''
        }
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleItemClick = this.handleItemClick.bind(this);
    }
    handleInputChange (e) {
        this.setState({
            inputValue: e.target.value
        })
    }
     handleBtnClick () {
        this.setState({
            list: [...this.state.list, this.state.inputValue],
            inputValue: ''           // 清空输入框
        })
     }
    handleItemClick (index) {
        const list = [...this.state.list];   // 尽量不要直接用state里面的数据，可调式性好
        list.splice(index,1)
        this.setState({
            list,
        })
    }
    // 拆分
    getTodoItems () {
        return (
            this.state.list.map((item, index) => {
                // return <li key={index} onClick={this.handleItemClick.bind(this,index)}>{item}</li>
                return(
                    <TodoItem key={index}
                              content={item}
                              index={index}
                              handleDetete={this.handleItemClick}
                    />     // 父组件通过属性的形式向子组件传递参数，子组件通过props接受父组件传递过来的参数
                );
            })
        )
    }
      render() {
        return (
            <Fragment>
              <div>
                <input value={this.state.inputValue} onChange={this.handleInputChange}/>
                <button className='button' style={{background: 'yellow'}} onClick={this.handleBtnClick}>add</button>
              </div>
              <ul>
                  {this.getTodoItems()}
              </ul>
            </Fragment>

        )
      }
}
export default TodoList;
